//
//  InvitationvViewController.m
//  Fengshui
//
//  Created by are on 13-5-30.
//
//

#import "InvitationvViewController.h"

@interface InvitationvViewController ()

@end

@implementation InvitationvViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (SinaWeibo *)sinaweibo
{
    AppDelegate  *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    delegate.sinaweibo.delegate = self;
    return delegate.sinaweibo;
}
- (void) sendTextContent:(NSString*)nsText
{
    SendMessageToWXReq* req = [[[SendMessageToWXReq alloc] init]autorelease];
    req.bText = YES;
    req.text = nsText;
    req.scene = WXSceneSession;

    [WXApi sendReq:req];
}
-(IBAction)weixinBtnAction:(id)sender
{
    AppDelegate *delegate =  [[UIApplication sharedApplication] delegate];
    delegate.sinaOrWeixin = YES;
    [self sendTextContent:@"我正在玩卜卜,可以算算运势，看风水，非常有意思，你也下一个一起玩啊!"];
    
}
-(IBAction)typeBtnAction:(id)sender
{
    UIButton *button = (UIButton *)sender;
    
    if (button.tag == 1) {

        if (self.TXLcontroller) {
            [self.view bringSubviewToFront:self.TXLcontroller.view];
        }
        
    }
    else if(button.tag == 2)
    {

        if (self.sinaFriendTableView.superview) {

             [self.view bringSubviewToFront:self.sinaFriendTableView];
        }
        
        SinaWeibo *sinaweibo = [self sinaweibo];
        if (![sinaweibo isAuthValid])
        {
            if (self.bundlingView.superview) {

                [self.view bringSubviewToFront:self.bundlingView];
            }
            else
            {
                [self.bundlingView setFrame:CGRectMake(0, 56, 320, self.bundlingView.frame.size.height)];
            }
            [self.view addSubview:self.bundlingView];
            [self.view bringSubviewToFront:self.bundlingView];
}

        else
        {
//            get
//            请求URL：https://api.weibo.com/2/friendships/friends.json
//            请求参数：uid=1870632073&access_token=2.00rHyDrCWHsSFDf8ca9ad11fKtRQeB
            if ([self.sinaFriendInfoArray count]==0) {

                [self requestSinaFrendINFO];
            }
            
        }
    }
    else if (button.tag == 3)
    {
        if (!self.invateWeiXin.superview) {

            [self.invateWeiXin setFrame:CGRectMake(0, 56, 320, self.view.frame.size.height-56)];
            [self.view addSubview:self.invateWeiXin];
        }
        [self.view bringSubviewToFront:self.invateWeiXin];

        
    }
}
-(void)requestSinaFrendINFO
{
    SinaWeibo *sinaweibo = [self sinaweibo];
    NSString *string = [NSString stringWithFormat:@"https://api.weibo.com/2/friendships/friends.json?uid=%@&access_token=%@&count=50&cursor=%d",sinaweibo.userID,sinaweibo.accessToken,self.youbiaoNum];
    NSURL *url = [NSURL URLWithString:string];
    Dlog(@"%@",url);
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    self.isLoading = YES;
    [request setDelegate:self];
    [request startAsynchronous];
    
}
#pragma sinaWeiboDelegate ,ASIhttpRequest
- (void)storeAuthData
{
    SinaWeibo *sinaweibo = [self sinaweibo];

    NSDictionary *authData = [NSDictionary dictionaryWithObjectsAndKeys:
                              sinaweibo.accessToken, @"AccessTokenKey",
                              sinaweibo.expirationDate, @"ExpirationDateKey",
                              sinaweibo.userID, @"UserIDKey",
                              sinaweibo.refreshToken, @"refresh_token", nil];
    [[NSUserDefaults standardUserDefaults] setObject:authData forKey:@"SinaWeiboAuthData"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    

}
- (void)sinaweiboDidLogIn:(SinaWeibo *)sinaweibo
{

    [self storeAuthData];
    if (!self.sinaFriendTableView.superview) {

        [self.sinaFriendTableView setFrame:CGRectMake(0, 56, 320, self.view.frame.size.height-56)];
        [self.view addSubview:self.sinaFriendTableView];
    }
    [self.view bringSubviewToFront:self.sinaFriendTableView];
    NSString *string = [NSString stringWithFormat:@"https://api.weibo.com/2/friendships/friends.json?uid=%@&access_token=%@",sinaweibo.userID,sinaweibo.accessToken];
    
    NSURL *url = [NSURL URLWithString:string];
    Dlog(@"%@",url);
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setDelegate:self];
    [request startAsynchronous];
    
    
}
- (void)sinaweiboDidLogOut:(SinaWeibo *)sinaweibo
{
    
}
- (void)sinaweiboLogInDidCancel:(SinaWeibo *)sinaweibo
{
    
}
- (void)sinaweibo:(SinaWeibo *)sinaweibo logInDidFailWithError:(NSError *)error
{
    
}
- (void)sinaweibo:(SinaWeibo *)sinaweibo accessTokenInvalidOrExpired:(NSError *)error
{
    
}
-(void)requestFailed:(ASIHTTPRequest *)request
{
    self.isLoading = NO;
}
-(void)requestFinished:(ASIHTTPRequest *)request
{
    self.isLoading = NO;
    Dlog(@"%@",[request responseString]);
    NSString *string = [request responseString];
    NSDictionary *dic = [string JSONValue];
    self.totalNum = [[dic objectForKey:@"total_number"] intValue];
    self.youbiaoNum = [[dic objectForKey:@"next_cursor"] intValue];
    NSArray *array = [dic objectForKey:@"users"];
    if ([array count]<50) {

        self.contnueGet = YES;
    }
    [self.sinaFriendInfoArray addObjectsFromArray:array];
    if (!self.sinaFriendTableView.superview) {

        [self.sinaFriendTableView setFrame:CGRectMake(0, 56, 320, self.view.frame.size.height-56)];
        [self.view addSubview:self.sinaFriendTableView];
    }
    [self.view bringSubviewToFront:self.sinaFriendTableView];
    [self.sinaFriendTableView reloadData];

}
//- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//    if (isLoading && scrollView.contentOffset.y > 0) {
//        // Update the content inset, good for section headers
//        self.tableView.contentInset = UIEdgeInsetsMake(0, 0, REFRESH_HEADER_HEIGHT, 0);
//    }else if(!hasMore){
//        refreshLabel.text = self.textNoMore;
//        refreshArrow.hidden = YES;
//    }else if (isDragging && scrollView.contentSize.height - (scrollView.contentOffset.y + scrollView.bounds.size.height - scrollView.contentInset.bottom) <= 0 ) {
//        // Update the arrow direction and label
//        [UIView beginAnimations:nil context:NULL];
//        refreshArrow.hidden = NO;
//        if (scrollView.contentSize.height - (scrollView.contentOffset.y + scrollView.bounds.size.height - scrollView.contentInset.bottom) <= -REFRESH_HEADER_HEIGHT) {
//            // User is scrolling above the header
//            refreshLabel.text = self.textRelease;
//            [refreshArrow layer].transform = CATransform3DMakeRotation(M_PI, 0, 0, 1);
//        } else { // User is scrolling somewhere within the header
//            refreshLabel.text = self.textPull;
//            [refreshArrow layer].transform = CATransform3DMakeRotation(M_PI * 2, 0, 0, 1);
//        }
//        [UIView commitAnimations];
//    }
//}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {


    if (self.contnueGet == YES) {

        return;

    }
    if(scrollView.contentSize.height - (scrollView.contentOffset.y + scrollView.bounds.size.height - scrollView.contentInset.bottom) <= -REFRESH_HEADER_HEIGHT && scrollView.contentOffset.y > 0){
        [self requestSinaFrendINFO];
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   return [self.sinaFriendInfoArray count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    WeiboHaoyouCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {

        cell = [[[NSBundle mainBundle] loadNibNamed:@"WeiboHaoyouCell" owner:self options:nil] objectAtIndex:0];
    }
    NSDictionary *dic = [self.sinaFriendInfoArray objectAtIndex:indexPath.row];
    NSString *imageStr = [dic objectForKey:@"profile_image_url"];
    NSURL *url = [NSURL URLWithString:imageStr];
    [cell.pictureView setImageWithURL:url
                     placeholderImage:[UIImage imageNamed:@"tongxunludefault.jpg"]];
    cell.nameLabel.text = [dic objectForKey:@"screen_name"];
    cell.cellIndex = indexPath.row;
    //NSString *string = @"邀请";
    [cell.inviteBtn.titleLabel setTextColor:[UIColor blackColor]];
    [cell.inviteBtn setTitle:@"邀请" forState:UIControlStateNormal];
    cell.inviteBtn.tag = 1;
    cell.delegate = self;
    return cell;
    
}

#pragma ------delegate
-(void)inviteBtnAction:(NSInteger)cellIndex
{
    TextViewController* viewController = [[[TextViewController alloc] init] autorelease];
    viewController.m_nsLastText = [NSString stringWithFormat:@"@%@ 我正在使用卜卜，可以算运势，看风水，超有意思的，赶紧下一个一起玩吧",[[self.sinaFriendInfoArray objectAtIndex:cellIndex] objectForKey:@"screen_name"]];
    
    UINavigationController *navigatitonController = [[[UINavigationController alloc]initWithRootViewController:viewController] autorelease];
	[self presentModalViewController:navigatitonController animated:YES];
}
#pragma -----
-(IBAction)bundlingBtnAction:(id)sender
{
    SinaWeibo *sinaweibo = [self sinaweibo];
    [sinaweibo logIn];
    
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.totalNum = 0;
    self.youbiaoNum = 0;
    self.sinaFriendInfoArray = [NSMutableArray array];
     self.TXLcontroller = [[TongxunluViewController alloc] initWithNibName:@"TongxunluViewController" bundle:nil];
    [self.TXLcontroller.view setFrame:CGRectMake(0, 56, 320,self.view.frame.size.height-56)];
    [self.view addSubview:self.TXLcontroller.view];
    self.TXLcontroller.parentViewController = self;
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
